/**
 * Copyright (c) 2018 人人开源 All rights reserved.
 * <p>
 * https://www.renren.io
 * <p>
 * 版权所有，侵权必究！
 */

package cn.kgm.generator.controller;

import cn.hutool.core.text.StrPool;
import cn.kgm.generator.entity.GenDTO;
import cn.kgm.generator.service.SysGeneratorService;
import cn.kgm.generator.utils.GenR;
import cn.kgm.generator.utils.PageUtils;
import cn.kgm.generator.utils.Query;
import org.apache.commons.io.IOUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Controller;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestParam;
import org.springframework.web.bind.annotation.ResponseBody;

import javax.servlet.http.HttpServletResponse;
import java.io.IOException;
import java.util.Map;

/**
 * 代码生成器
 *
 * @author Mark sunlightcs@gmail.com
 */
@Controller
@RequestMapping("/sys/generator")
public class SysGeneratorController {
	@Autowired
	private SysGeneratorService sysGeneratorService;

    /**
     * 列表
     */
    @ResponseBody
    @RequestMapping("/list")
    public GenR list(@RequestParam Map<String, Object> params) {
        PageUtils pageUtil = sysGeneratorService.queryList(new Query(params));
        return GenR.ok().put("page", pageUtil);
    }

    /**
     * 生成代码
     */
    @RequestMapping("/code")
    public void code(@RequestParam("tables") String tables,
                     @RequestParam("basePackageName") String basePackageName,
                     @RequestParam("author") String author,
                     @RequestParam("tablePrefix") String tablePrefix,
                     @RequestParam("moduleName") String moduleName,
                     HttpServletResponse response) throws IOException {
        byte[] data = sysGeneratorService.generatorCode(GenDTO.builder()
                .tables(tables.split(StrPool.COMMA))
                .basePackageName(basePackageName)
                .auther(author)
                .tablePrefix(tablePrefix.split(StrPool.COMMA))
                .moduleName(moduleName)
                .build());

        response.reset();
        response.setHeader("Content-Disposition", "attachment; filename=\"generator.zip\"");
        response.addHeader("Content-Length", "" + data.length);
        response.setContentType("application/octet-stream; charset=UTF-8");

        IOUtils.write(data, response.getOutputStream());
    }
}
